package org.fu.crowd.controller;

import org.fu.crowd.api.MySQLRemoteService;
import org.fu.crowd.api.RedisRemoteService;
import org.fu.crowd.constant.CrowdConstant;
import org.fu.crowd.po.Member;
import org.fu.crowd.utils.Common;
import org.fu.crowd.utils.CrowdUtils;
import org.fu.crowd.vo.MemberLoginV0;
import org.fu.crowd.vo.MemberVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Controller
public class PortalController {


    //redis接口
    @Autowired
    private RedisRemoteService redisRemoteService;

    //mysql接口
    @Resource
    private MySQLRemoteService mySQLRemoteService;

    /**
     *      验证码请求
     */
    @ResponseBody
    @RequestMapping("/register/getPhoneCode")
    public Common<String> getPhoneCode(@RequestParam("phoneNum")String phoneNum){
        if (phoneNum==null||phoneNum.length()<11){
            return Common.failed("请输入正确的手机号");
        }
        //发送验证码到手机
        Common<String> phoneCommon = CrowdUtils.sendCodeShortMessage(phoneNum);
        //判断发送的结果
        if (Common.SUCCESS.equals(phoneCommon.getResult())){
            //发送成功将验证码存入redis
            String code = phoneCommon.getData();
            String phoneKey = CrowdConstant.REDIS_CODE_PREFIX+phoneNum;
            Common<String> redisCommon = redisRemoteService.setRedisKeyValueRemoteWithTimeOutRemote(phoneKey, code, 5L, TimeUnit.MINUTES);
            //是否保存成功
            if (Common.SUCCESS.equals(redisCommon.getResult())){
                return Common.successWithoutData();
            }else {
                return redisCommon;
            }
        }else {
            return phoneCommon;
        }
    }







    /**
     *  保存用户信息
     */
    @RequestMapping("/saveRegister")
    public String saveRegister(MemberVO memberVO, Model model){
        //根据传入的手机号，拼接验证码在redis中的key
        String phoneNum = memberVO.getPhoneNum();
        String redisPhoneNumKey = CrowdConstant.REDIS_CODE_PREFIX+phoneNum;
        //根据key找到redis中对应的验证码值
        Common<String> redisCommon = redisRemoteService.getRedisValueByKeyRemote(redisPhoneNumKey);
        //判断redis中的验证码的有效性，   要不为null
        String result = redisCommon.getResult();
        //如果redis查找返回success
        if (Common.SUCCESS.equals(result)){
            String redisCode = redisCommon.getData();
            //redis查找结果判断
            if (redisCode == null || redisCode.length() < 4){
                model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_CODE_NOT_EXISTS);
                model.addAttribute("registerMember",memberVO);
                return "register";
            } else{
                //与用户输入的进行比较
                String formCode = memberVO.getCode();
                if (Objects.equals(formCode,redisCode)){
                    //验证码一致，删除redis中保存的验证码
                    redisRemoteService.removeRedisValueByKeyRemote(redisPhoneNumKey);
                    //进行密码加密
                    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
                    String userpswd = memberVO.getUserpswd();
                    userpswd = bCryptPasswordEncoder.encode(userpswd);
                    memberVO.setUserpswd(userpswd);
                    //执行保存操作
                    Member member = new Member();
                    BeanUtils.copyProperties(memberVO,member);
                    Common<String> mysqlSaveCommon = mySQLRemoteService.saveMemberRemote(member);
                    //若保存失败
                    if (Common.FAILED.equals(mysqlSaveCommon.getResult())){
                        model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,mysqlSaveCommon.getMessage());
                        model.addAttribute("registerMember",memberVO);
                        return "register";
                    }
                }else {
                    model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_CODE_FAILED);
                    model.addAttribute("registerMember",memberVO);
                    return "register";
                }
            }
        }else {
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,redisCommon.getMessage());
            model.addAttribute("registerMember",memberVO);
            return "register";
        }
        return "redirect:/member/login";
    }





    /**
     *      用户登录请求
     */
    @RequestMapping("/member/doLogin")
    public String memberDoLogin(@RequestParam("loginacct")String loginacct, HttpSession session,
                                @RequestParam("userpswd")String userpswd, Model model){
        System.out.println("进来登录");
        //根据账号查询账号信息
        Common<Member> memberPOCommon = mySQLRemoteService.getMemberPOByLoginAcctRemote(loginacct);
        //判断是否查询成功
        if (Common.FAILED.equals(memberPOCommon.getResult())){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_LOGIN_FAILED);
            return "member-login";
        }
        //如果返回success
        Member member = memberPOCommon.getData();
        if (member == null){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_LOGIN_FAILED);
            return "member-login";
        }
        //比较密码
        String userpswdDB = member.getUserpswd();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean matches = bCryptPasswordEncoder.matches(userpswd, userpswdDB);
        if (!matches){
            model.addAttribute(CrowdConstant.ATTR_NAME_MESSAGE,CrowdConstant.MESSAGE_LOGIN_FAILED);
            return "member-login";
        }
        //创建MemberLoginV0对象并存入session中
        MemberLoginV0 memberLoginV0 = new MemberLoginV0(member.getId(),member.getUsername(),member.getEmail());
        session.setAttribute(CrowdConstant.LOGIN_MEMBER,memberLoginV0);
        System.out.println("已保存，"+memberLoginV0);
        return "redirect:/member";
    }





    /**
     *  退出登录
     */
    @RequestMapping("/member/logout")
    public String memberLogout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }




}
